package com.zhu.salesmanagement;

import java.util.ArrayList;
import java.util.List;

import com.zhu.salesmanagement.ProductsListActivity.ItemInfo;
import com.zhu.salesmanagement.ProductsListActivity.MyImgAdapter;
import com.zhu.salesmanagement.common.Actions;
import com.zhu.salesmanagement.models.CustomerItem;
import com.zhu.salesmanagement.models.VisitTaskInfo;
import com.zhu.salesmanagement.provider.SalesSettings;
import com.zhu.salesmanagement.utils.DialogUtil;

import android.app.Activity;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.AdapterView;
import android.widget.TextView;

/**
 * 数据核查界面
 */

public class CustomersListActivity extends Activity implements AdapterView.OnItemClickListener, View.OnClickListener{

	private final static int C_LIST_QUERY_TOKEN = 0;
	private final static int C2_LIST_QUERY_TOKEN = 1;
	private final static int C3_LIST_QUERY_TOKEN = 3;
	private final static int C4_LIST_QUERY_TOKEN = 4;

	private final static int TYPE_CHANPING = 0;
	private final static int TYPE_DALEI = 1;
	private final static int TYPE_KEHU = 2;

	private ListView mChanpinListView = null; //产品信息
	private ListView mKehuListView = null; //客户信息
	private ListView mDaleiListView = null; //产品大类信息
	private boolean mSynced_Chanping = false;
	private boolean mSynced_dalei = false;
	private boolean mSynced_kehu= false;
	private List<CustomerItem> mDaleiList = new ArrayList<CustomerItem>();
	

	private ListQueryHandler mListQueryHandler = null;

	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.layout_listview);
        findViewById(R.id.chanpin).setOnClickListener(this);
        findViewById(R.id.dalei).setOnClickListener(this);
        findViewById(R.id.kehu).setOnClickListener(this);
        findViewById(R.id.visit_back).setOnClickListener(this);

        mChanpinListView = (ListView)findViewById(R.id.chanpin_listview);
        mChanpinListView.setOnItemClickListener(this);
        mDaleiListView = (ListView)findViewById(R.id.dalei_listview);
        mDaleiListView.setOnItemClickListener(this);
        mKehuListView = (ListView)findViewById(R.id.kehu_listview);
        mKehuListView.setOnItemClickListener(this);
        mListQueryHandler = new ListQueryHandler(this.getContentResolver());

        startSyncChanpin();
    }

	/**
	 * 获取大类数据
	 */
	private void startSyncDalei(){
	    mListQueryHandler.startQuery(C4_LIST_QUERY_TOKEN, null, SalesSettings.ProductShelfsColumns.CONTENT_URI, 
                null, null, null, null);
	}
	
	/**
	 * 获取产品
	 */
	private void startSyncChanpin(){
        mListQueryHandler.startQuery(C2_LIST_QUERY_TOKEN, null, SalesSettings.ProductsColumns.CONTENT_URI, 
                null, null, null, null);
    }

	/**
	 * 获取客户数据
	 */
	private void startSyncKehu(){
		mListQueryHandler.startQuery(C_LIST_QUERY_TOKEN, null, SalesSettings.CustomerSColumns.CONTENT_URI, 
				null, null, null, null);
	}

	public void onResume() {
        super.onResume();
        Actions.setAutoTime(this);
    }

	/**
	 * 初始化客户数据
	 * @param cursor 客户数据库数据
	 */
	private void initCustomerList(Cursor cursor){
	    List<CustomerItem> mList = new ArrayList<CustomerItem>();
		try {
            final int idIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns._ID);
            final int storeidIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_ID);
            final int nameIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_NAME);
            final int typeIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_VISITCODE);
            final int latIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_LAT);
            final int lngIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_LNG);
            final int addrIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_ADDRESS);

            while (cursor.moveToNext()) {
           		CustomerItem visitTaskInfo = new CustomerItem();
           		visitTaskInfo.mType = TYPE_KEHU;
           		visitTaskInfo.sCustomerID = cursor.getString(storeidIndex);
            	visitTaskInfo.sCustomerName = cursor.getString(nameIndex)+ "," + cursor.getString(storeidIndex);
            	visitTaskInfo.sCustomerAddress = cursor.getString(addrIndex);
            	visitTaskInfo.sStoreCategory = cursor.getString(typeIndex);
            	visitTaskInfo.sLatitude = cursor.getString(latIndex);
            	visitTaskInfo.sLongitude = cursor.getString(lngIndex);
            	mList.add(visitTaskInfo);
            	
            	updateCustomerItem(cursor.getString(storeidIndex), cursor.getString(nameIndex)+ "," + cursor.getString(storeidIndex), 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("zhu", "updateStoreInfoList error");
        } finally {
            if(cursor != null){
                cursor.close();
                cursor = null;
            }
        }
        mSynced_kehu = true;
        mKehuListView.setAdapter(new MyImgAdapter(mList));
        mSynced_dalei = true;
        mDaleiListView.setAdapter(new MyImgAdapter(mDaleiList));
	}

	/**
	 * 初始化产品数据
	 * @param cursor 产品数据库数据
	 */
	private void initChanpinList(Cursor cursor){
	    List<CustomerItem> mList = new ArrayList<CustomerItem>();
	    try {
            final int idIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductsColumns._ID);
            final int pidIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductsColumns.PRODUCT_ID);
            final int proidIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductsColumns.PRODUCTCATEGORY_ID);
            final int nameIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductsColumns.PRODUCT_NAME);

            while (cursor.moveToNext()) {
                CustomerItem visitTaskInfo = new CustomerItem();
                visitTaskInfo.mType = TYPE_CHANPING;
                visitTaskInfo.sCustomerName = cursor.getString(nameIndex);
                visitTaskInfo.sCustomerAddress = cursor.getString(pidIndex) +"  ,  " +cursor.getString(proidIndex);
                mList.add(visitTaskInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("zhu", "updateStoreInfoList error");
        } finally {
            if(cursor != null){
                cursor.close();
                cursor = null;
            }
        }
        mChanpinListView.setAdapter(new MyImgAdapter(mList));
	}

	/**
	 * 初始化大类
	 * @param cursor 大类数据库数据
	 */
	private void initDaleiList(Cursor cursor){
        try {
            final int storeidIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductCategoryColumns.PRODUCTCATEGORY_ID);
            final int nameIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductCategoryColumns.PRODUCTCATEGORY_NAME);

            while (cursor.moveToNext()) {
                updateCustomerItem(cursor.getString(storeidIndex), cursor.getString(nameIndex), 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("zhu", "updateStoreInfoList error");
        } finally {
            if(cursor != null){
                cursor.close();
                cursor = null;
            }
        }
        startSyncKehu();
    }

	/**
	 * 初始化门店下大类数据
	 * @param cursor 门店大类数据库数据
	 */
	private void initDaleiaaaList(Cursor cursor){
	    mDaleiList.clear();
        try {
            final int pcIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductShelfsColumns.PRODUCTCATEGORY_ID);
            final int storeidIndex = cursor.getColumnIndexOrThrow(SalesSettings.ProductShelfsColumns.CUSTOMER_ID);

            while (cursor.moveToNext()) {
                CustomerItem visitTaskInfo = new CustomerItem();
                visitTaskInfo.mType = TYPE_DALEI;
                visitTaskInfo.sCustomerID = cursor.getString(storeidIndex);
                visitTaskInfo.pcid = cursor.getString(pcIndex);
                mDaleiList.add(visitTaskInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("zhu", "updateStoreInfoList error");
        } finally {
            if(cursor != null){
                cursor.close();
                cursor = null;
            }
        }
        mListQueryHandler.startQuery(C3_LIST_QUERY_TOKEN, null, SalesSettings.ProductCategoryColumns.CONTENT_URI, 
                null, null, null, null);
        //mSynced_dalei = true;
        //mDaleiListView.setAdapter(new MyImgAdapter(mList));
    }

	private CustomerItem getCustomerItem(String pcid, int type){
	    for(int i = 0; i < mDaleiList.size(); i++){
	        CustomerItem item = mDaleiList.get(i);
	        if(type == 1){
	            if(item.pcid.equals(pcid)){
	                return item;
	            }
	        }else{
	            if(item.sCustomerID.equals(pcid)){
	                return item;
	            }
	        }
	    }
	    return null;
	}

	/**
	 * 初始化门店下大类数据
	 * @param pcid 大类ID
	 * @param pcname 大类名字
	 *  @param type 类型
	 */
	private void updateCustomerItem(String pcid, String pcname, int type){
	    for(int i = 0; i < mDaleiList.size(); i++){
            CustomerItem item = mDaleiList.get(i);
            if(type == 1){
                if(item.pcid.equals(pcid)){
                    item.sCustomerAddress = pcname;
                }
            }else{
                if(item.sCustomerID.equals(pcid)){
                    item.sCustomerName = pcname;
                }
            }
        }
	}

	private final class ListQueryHandler extends AsyncQueryHandler {
        public ListQueryHandler(ContentResolver contentResolver) {
            super(contentResolver);
        }

        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            switch (token) {
                case C_LIST_QUERY_TOKEN: //客户查询结果
                    initCustomerList(cursor);
                    break;
                case C2_LIST_QUERY_TOKEN: //产品查询结果
                    initChanpinList(cursor);
                    break;
                case C3_LIST_QUERY_TOKEN: //大类查询结果
                    initDaleiList(cursor);
                    break;
                case C4_LIST_QUERY_TOKEN: //客户大类查询结果
                    initDaleiaaaList(cursor);
                    break;
            }
        }

        @Override
        protected void onDeleteComplete(int token, Object cookie, int result) {

        }
    }

	public final class ViewHolder{
		public TextView text1;
		public TextView text2;
		public CustomerItem mCustomerItem;
	}

	
	class MyImgAdapter extends BaseAdapter {

	    private List<CustomerItem> mList = null;

		public MyImgAdapter(List<CustomerItem> list) {
			super();
			mList = list;
		}

		@Override
		public int getCount() {
			return mList.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;

			if (convertView == null) {
				convertView = LayoutInflater.from(CustomersListActivity.this)
						.inflate(R.layout.layout_listviewitem, null);
				holder = new ViewHolder();
				holder.text1 = (TextView) convertView.findViewById(R.id.text1);
				holder.text2 = (TextView) convertView.findViewById(R.id.text2);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.text1.setText(mList.get(position).sCustomerName);
			holder.text2.setText(mList.get(position).sCustomerAddress);
			return convertView;
		}

	}


	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
//		CustomerItem visitTaskInfo = mList.get(arg2);
//		String content = visitTaskInfo.sCustomerID +"\n" + visitTaskInfo.sLatitude + "\n" +visitTaskInfo.sLongitude +"\n";
//		DialogUtil.getSimpleDialog(CustomersListActivity.this,
//				visitTaskInfo.sCustomerName,
//				content, null).show();
	}

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (v != null) {
            switch (v.getId()) {
                case R.id.chanpin: //产品
                    mChanpinListView.setVisibility(View.VISIBLE);
                    mKehuListView.setVisibility(View.INVISIBLE);
                    mDaleiListView.setVisibility(View.INVISIBLE);
                    break;
                case R.id.dalei: //大类
                    if(!mSynced_dalei){
                        startSyncDalei();
                    }
                    mChanpinListView.setVisibility(View.INVISIBLE);
                    mKehuListView.setVisibility(View.INVISIBLE);
                    mDaleiListView.setVisibility(View.VISIBLE);
                    break;
                case R.id.kehu: //客户
                    if(!mSynced_kehu){
                        startSyncKehu();
                    }
                    mChanpinListView.setVisibility(View.INVISIBLE);
                    mKehuListView.setVisibility(View.VISIBLE);
                    mDaleiListView.setVisibility(View.INVISIBLE);
                    break;
                case R.id.visit_back:
                    this.finish();
                    break;
            }
        }
    }
}
